package com.gu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gu.entity.EduSubject;
import com.gu.entity.excel.ExcelSubjectData;
import com.gu.entity.subject.TreeSubject;
import com.gu.listener.ExcelListener;
import com.gu.service.EduSubjectService;
import com.gu.mapper.EduSubjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject>
        implements EduSubjectService {

    @Override
    public void batchImport(MultipartFile file) {
        try {
            //1.获取文件路径或者文件流，此处应该采用 流
            InputStream inputStream = file.getInputStream();
            //2.读取文件
            EasyExcel.read(inputStream, ExcelSubjectData.class, new ExcelListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<TreeSubject> getAllSubject() {

        List<TreeSubject> treeSubjectList = new ArrayList<>();

        //先获取所有后遍历循环再查二级后赋值：
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", "0");
        List<EduSubject> list = this.list(wrapper);
        list.forEach(eduSubject -> {

            List<TreeSubject> secondTreeSubjectList = new ArrayList<>();

            //每个一级目录所含的所有二级课程
            TreeSubject treeSubject = new TreeSubject();
            QueryWrapper<EduSubject> secondWrapper = new QueryWrapper<>();
            secondWrapper.eq("parent_id",eduSubject.getId());
            List<EduSubject> secondList = this.list(secondWrapper);

            //二级目录所有课程
            secondList.forEach(secondSubject -> {
                TreeSubject secondTreeSubject = new TreeSubject();
                secondTreeSubject.setId(secondSubject.getId());
                secondTreeSubject.setTitle(secondSubject.getTitle());
                secondTreeSubjectList.add(secondTreeSubject);
            });
            treeSubject.setId(eduSubject.getId());
            treeSubject.setTitle(eduSubject.getTitle());
            treeSubject.setChildren(secondTreeSubjectList);
            treeSubjectList.add(treeSubject);
        });

        return treeSubjectList;
    }
}




